import { http } from "@/utils/http";
import { baseUrlApi, sysUrlApi } from "./utils";

type TreeNode = {
  name: string;
  type: number; // 1 公司 2 分公司 3 部门
  parentId: number;
  sort: number;
  leaderUserId: number;
  phone: string;
  email: string;
  status: number;
  id: number;
  createTime: number;
  remark: string;
};

export type deptForm = {
  deptId: string;
  deptName: string;
  parentId: string;
  maxUserNum: number;
  status: number;
};

export const getDeptPage = (data?: object) => {
  return http.request<Array<any>>("get", sysUrlApi("org/list"), { data });
};
export const addDept = (data?: deptForm) => {
  return http.request("post", baseUrlApi("dept"), { data });
};

export const updateDept = (data?: deptForm) => {
  return http.request("put", baseUrlApi("dept"), { data });
};

export const deleteDept = (deptId?: string, del?: string) => {
  return http.request("delete", baseUrlApi("dept/" + deptId + "/" + del));
};

export const transitionTreeData = (r: Array<any>) => {
  const li: TreeNode[] = [];
  r.forEach(item => {
    if (item.deptId != "2") {
      li.push({
        name: item.deptName,
        type: 1, // 1 公司 2 分公司 3 部门
        parentId: item.parentId,
        sort: 0,
        leaderUserId: 1,
        phone: "",
        email: "",
        status: item.status,
        id: item.deptId,
        createTime: item.createdAt,
        remark: ""
      });
    }
  });
  return li;
};

export const simpleTransitionTree = data => {
  const cloneData = JSON.parse(JSON.stringify(data));
  return cloneData.filter(father => {
    const branchArr = cloneData.filter(
      child => father["deptId"] == child["parentId"]
    );
    branchArr.length > 0 ? (father["children"] = branchArr) : "";
    return father["parentId"] == "0";
  });
};
